function [lambda,fval] = PQP(Q,h,lambda0,t)
% Given Q, h, and initial guess lambda0, solve using the PQP algorithm.

tol = 1e-6;

numduals = length(lambda0);

cost0 = 1/2*lambda0'*Q*lambda0 + lambda0'*h + 1;
cost1 = 1/2*lambda0'*Q*lambda0 + lambda0'*h;

Qminus = (Q<0).*(-Q);
% r = Qminus*ones(numduals,1);
% r = Qminus*ones(numduals,1)+1;
r = zeros(numduals,1);
Qminus = (Q<0).*(-Q) + diag(r);
Qplus = (Q>0).*Q + diag(r);

hminus = (h<0).*(-h);
hplus = (h>0).*h;

% Make sure all lambda(i)>0
lambda = (lambda0==0)+lambda0;

ftemp = cost1;

while(abs(cost0-cost1)>tol)
    % update duals
    num = (Qminus*lambda0 + hminus);
    den = (Qplus*lambda0 + hplus);
    for i = 1:numduals
        if(den(i)==0)
%             disp('ackkkk freak outttt')
            if(lambda(i)~=0)
%               disp('lambda is 0')
                lambda(i) = 0;
            end
        else
        lambda(i) = lambda0(i)*num(i)/den(i);
        end
    end
    
    % update cost and lambda0
    cost0 = cost1;
    cost1 = 1/2*lambda'*Q*lambda + lambda'*h;
    lambda0 = lambda;
    ftemp = [ftemp,cost1];
end
% 
% if t>=43
%     lambda
%     cost1
%     r
% end

% for i = 1:length(ftemp)
%     fprintf('%0.8f\n',ftemp(i));
% end

niter = length(ftemp)

fval = cost1;